$package("wstuo.noticeRule");

$import('wstuo.user.userUtil');
/**  
 * @author WSTUO  
 * @constructor 
 * @description "noticeGrid"

 */ 
wstuo.noticeRule.noticeGrid = function(){
	var noticeId="";
	this.variables = {
			ecode:'<option value="{variables.ecode}">'+i18n.number+'</option>',
			etitle:'<option value="{variables.etitle}">'+i18n.title+'</option>',
			edesc:'<option value="{variables.edesc}">'+i18n.description+'</option>',
			ecategoryName:'<option value="{variables.ecategoryName}">'+i18n.label_sla_ecategory+'</option>',
			createdByName:'<option value="{variables.createdByName}">'+i18n.requester+'</option>',
			historyRecord:'<option value="historyRecord">'+i18n.title_request_history+'</option>',
			/*seriousnessName:'<option value="{variables.seriousnessName}">'+i18n.label_dc_seriousness+'</option>',*/
			priorityName:'<option value="{variables.priorityName}">'+i18n.label_dc_priority+'</option>',
			statusName:'<option value="{variables.statusName}">'+i18n.status+'</option>',
			/*imodeName:'<option value="{variables.imodeName}">'+i18n.label_sla_imode+'</option>',
			levelName:'<option value="{variables.levelName}">'+i18n.label_sla_level+'</option>',*/
			assigneeGroupName:'<option value="{variables.assigneeGroupName}">'+i18n.label_request_assignGroup+'</option>',
			assigneeName:'<option value="{variables.technicianName}">'+i18n.label_request_assigner+'</option>',
			solutions:'<option value="{variables.solutions}">'+i18n.label_solutions+'</option>',
			createDate:'<option value="createDate">'+i18n.custom_report_task_date+'</option>',
			ciname:'<option value="{variables.ciname}">'+i18n.label_dynamicReports_change_ciname+'</option>',
			outcome:'<option value="{variables.outcome}">'+i18n.changeAction+'</option>',
			activityName:'<option value="{variables.activityName}">'+i18n.label_bpm_task_name+'</option>',
			operator:'<option value="{variables.operator}">'+i18n.label_request_operationUser+'</option>',
			planTime:'<option value="{variables.planTime}">'+i18n.plan_Date+'</option>',
			cimInfos:'<option value="cimInfos">'+i18n.ci_configureItemInfo+'</option>',
			end:''
	};
	return{
		
		/**
		 * @description 格式化值
		 */
		inputSetValue:function(value){
			if(value==null || value=='null')
				return '';
			else
				return value;
		},
		/**
		 * 进入添加模板页面
		 */
		
		addNoticeModel:function(){
			var url="noticeRule!findByNoticesModel.action";
			basics.index.initContent(url);
			
		},
	
		/**
		 * 显示通知模板列表
		 */
		showNotice:function(){
			var _url="noticeRule!findPager.action";
			var params = $.extend({},jqGridParams, {
				url: _url,
				colNames:['ID',i18n.noticeRule_Name,i18n.notice_module,i18n.notice_noticeObject,i18n.noticeMethod,i18n.status,i18n.operateItems], 
				colModel:[
							{name:'noticeRuleId',width:50,align:'center',sortable:true},
							{name:'noticeRuleName',width:150,sortable:true},
							{name:'noticeRuleModule',index:'module',width:50,align:'center',sortable:true,formatter:wstuo.noticeRule.noticeGrid.moduleFormatter},
							{name:'noticeRuleType',width:100,align:'center',sortable:true,formatter:wstuo.noticeRule.noticeGrid.noticesTypeFormatter},
							{name:'noticeMethod',width:100,align:'center',sortable:false,formatter:wstuo.noticeRule.noticeGrid.noticeMethodFormatter},
							{name:'status',index:'useStatus',width:50,align:'center',sortable:true,formatter:wstuo.noticeRule.noticeGrid.statusFormatter},
							{name:'act', width:60,sortable:false,align:'center',formatter:function(cell,event,data){
							
								
								return '<div style="padding:0px">'+
								'<a href="javascript:wstuo.noticeRule.noticeGrid.confirmCheck(\''+(data.noticeRuleId)+'\')" plain="true" title='+i18n.edit+'><i class="glyphicon glyphicon-edit"></i></a>'+
								'&nbsp;&nbsp;&nbsp;<a href="javascript:wstuo.noticeRule.noticeGrid.delConfirmCheck(\''+(data.noticeRuleId)+'\')" plain="true" title='+i18n.deletes+'><i class="glyphicon glyphicon-trash"></i></a>'+
								'</div>';
							}}
						],
				jsonReader:$.extend({},jqGridJsonReader,{id:'noticeRuleId'}),
				sortname:'noticeRuleId',
				pager:'#noticeGridPager'
			});
			$("#noticeGrid").jqGrid(params);
			$("#noticeGrid").navGrid('#noticeGridPager',navGridParams);
			$("#t_noticeGrid").css(jqGridTopStyles);
			$("#t_noticeGrid").append($('#noticeGridToolbar').html());
			$("#noticeGrid_loading").attr("style","display:none");
		},
		/**
		 * 格式化状态
		 */
		statusFormatter:function(cell,event,data){
			if(data.useStatus){
				return i18n.enable;
			}else{
				return '<font color="red">'+i18n.disable+'</font>';
			}
		},
		/**
		 * 国际化
		 */
		noticeMethodFormatter:function(cell,event,data){
			var method = "";
			if(data.mailNotice){
				method +=i18n.notice_emailNotice+"；";
			}
			if(data.smsNotice){
				method +=i18n.notice_smsNotice+"；";
			}
			if(data.imNotice){
				method +=i18n.notice_imNotice+"；";
			}
			if(data.pushNotice){
				method +=i18n.notice_pushNotice+"；";
			}
			method = method.substring(0,method.length-1);
			return method;
		},
		moduleFormatter:function(cellvalue, options, rowObject){
			if(rowObject.module.indexOf("request")>=0){
				return i18n.request;
			}else if(rowObject.module.indexOf("problem")>=0){
				return i18n.problem;
			}else if(rowObject.module.indexOf("change")>=0){
				return i18n.change;
			}else if(rowObject.module.indexOf("cim")>=0){
				return i18n.CI;
			}else if(rowObject.module.indexOf("release")>=0){
				return i18n.release;
			}else if(rowObject.module.indexOf("task")>=0){
				return i18n.title_request_task;
			}else{
				return i18n.label_returnVisit_other;
			}
		},
		noticesTypeFormatter:function(cellvalue, options, rowObject){
			var noticeRuleType="";
			var data = rowObject.noticeRuleType;
			if(data.indexOf("requester")>=0){
				noticeRuleType +=i18n.notice_requester+"；";
			}
			if(data.indexOf("technician")>=0){
				noticeRuleType +=i18n.title_technician+"；";
			}
			if(data.indexOf("owner")>=0){
				noticeRuleType +=i18n.common_owner+"；";
			}
			if(data.indexOf("technicalGroup")>=0){
				noticeRuleType +=i18n.notice_technicalGroup+"；";
			}
			if(data.indexOf("taskGroupAndTechnician")>=0){
				noticeRuleType += i18n.lable_notice_technicalGroupOrTechnician+"；";
			}
			if(data.indexOf("taskTechnicalGroupLeader")>=0){
				noticeRuleType += i18n.able_bpm_assigneeGroupLeader+"；";
			}
			if(data.indexOf("ciOwner")>=0){
				noticeRuleType +=i18n.owner+"；";
			}
			if(data.indexOf("ciUse")>=0){
				noticeRuleType +=i18n.use+"；";
			}
			noticeRuleType = noticeRuleType.substring(0,noticeRuleType.length-1);
			return noticeRuleType;
		},
		
		confirmCheck:function(id){
			noticeId = id;
			
			basics.index.initContent("noticeRule!findByFileName.action?noticeRuleDTO.noticeRuleId="+id);
			
		},
		/**
		 * 执行查询
		 */
		doSearch:function(){
			var _url = 'noticeRule!findPager.action';
			var postData = $("#noticeGrid").jqGrid("getGridParam", "postData"); 
			var noticeRuleType="";
            $('input[name="noticeRuleTypeSeach"]:checked').each(function(){
				noticeRuleType+=$(this).val()+';';
            });
            noticeRuleType = noticeRuleType.substring(0,noticeRuleType.length-1);
			var status="";
			status=$('#useStatusSeach').val();
			var mailNotice="";
			if($('#mailNoticeSeach').attr("checked")){
				mailNotice=true;
			}
			var smsNotice="";
			if($('#smsNoticeSeach').attr("checked")){
				smsNotice=true;
			}
			var imNotice="";
			if($('#imNoticeSeach').attr("checked")){
				imNotice=true;
			}
			var pushNotice="";
			if($('#pushNoticeSeach').attr("checked")){
				pushNotice=true;
			}
			if(status=="all"){
				$.extend(postData,{'status':status,'noticeRuleDTO.noticeRuleName':$('#noticeNameSearch').val(),'noticeRuleDTO.module':$('#moduleSeach').val(),"noticeRuleDTO.noticeRuleType":noticeRuleType,'noticeRuleDTO.mailNotice':mailNotice,'noticeRuleDTO.smsNotice':smsNotice,'noticeRuleDTO.imNotice':imNotice,'noticeRuleDTO.pushNotice':pushNotice});
			}else{
				$.extend(postData,{'noticeRuleDTO.useStatus':status,'status':status,'noticeRuleDTO.noticeRuleName':$('#noticeNameSearch').val(),'noticeRuleDTO.module':$('#moduleSeach').val(),"noticeRuleDTO.noticeRuleType":noticeRuleType,'noticeRuleDTO.mailNotice':mailNotice,'noticeRuleDTO.smsNotice':smsNotice,'noticeRuleDTO.imNotice':imNotice,'noticeRuleDTO.pushNotice':pushNotice});
			}
			
			$('#noticeGrid').jqGrid('setGridParam',{page:1,url:_url}).trigger('reloadGrid');
		},
		/**
		 * 编辑通知模板
		 */
		editNotice:function(){

				var content=$("#emailEdit_templateContent").val();
				/*if(CKEDITOR.instances['emailEdit_templateContent']){
					var oEditor = CKEDITOR.instances.emailEdit_templateContent;
					content = oEditor.getData();
				}*/
	
				if(trim(content)==""){
					msgAlert(i18n.noticeRuleModule_Content_required,'info');
				}else{
					//if(wstuo.noticeRule.noticeGrid.haveOrNothave(content)){
						$('#emailEdit_templateContent').val(content);
						var noticeRuleType="";
	                    $('input[name="noticeRuleTypeEdit"]:checked').each(function(){
	                      noticeRuleType+=$(this).val()+';';
						});
						var mail = $("#emailMethodInput").val() ;
						var technicians = $("#technicianMethodInput").val();
						var fm = $('#editNoticesMethodForm').serialize()+'&'+$('#editNoticeMailFrom').serialize()+'&noticeRuleDTO.technician='+technicians+'&noticeRuleDTO.noticeRuleType='+noticeRuleType+'&noticeRuleDTO.emailAddress='+mail;
						validateUsersByLoginName(technicians,function(){
							if(checkEmail(mail,true)){
								startProcess();
								$.post("noticeRule!editNotice.action",fm, function(res){
									endProcess();//销毁
									
									basics.index.initContent("../pages/wstuo/sysMge/sysMge_noticeGrid.jsp");
									msgShow(i18n.editSuccess,'show');
								});
							}else{
								msgAlert(i18n.emailFormatError,'info');
							}
						});
					/*}else{
						msgAlert(i18n.contentHaveError,'error');
					}*/
				}

		},
		haveOrNothave:function(content){
		
			var beforeContent=content.substring(0,content.indexOf("<#escape"));
			var endContent=content.substring(content.indexOf("</#escape>")+10,content.length);
	
			if(beforeContent.indexOf("${")>0 || endContent.indexOf("${")>0){
			
				return false;
			}else{
				
				return true;
			}
		},
		/**
		 * 模板预览
		 */
		templatePreview:function(type,page){

			$("#templatePreviewDiv"+page).html("");
			var templateContent=$("#"+type+page+"_templateContent").val();
			
			$.post("noticeRule!templatePreview.action",{"templatesType":type,"contentString":templateContent},function(data){
				$("#templatePreviewDiv"+page).append("<div style=\"padding:5px;\">"+data+"</div>");
				windows('templatePreviewDiv'+page,{height:400});
			});
		},
		/**
		 * 
		 */
		getValue:function(name){
			var value='';
			var val=$("#variableValue"+name).val();
			if(val=="historyRecord"){
				value="<#if (variables.historyRecordDTO?exists && variables.historyRecordDTO?size>0) ><br><table class=\"table_border\">"+
						"<tr>"+
                        "<td>"+
                        i18n.label_request_action+
                        " </td>"+
                        "<td>"+
                        i18n.notice_detail+
                        "</td>"+
                        "<td>"+
                        i18n.label_request_operationUser+
                        "</td>"+
                        "<td>"+
                        i18n.label_request_operationTime+
                        "</td>"+
                        "</tr>"+
                        "<#list variables.historyRecordDTO as historyRecord>"+
                        "    <tr>"+
                        "        <td>"+
                        "            ${historyRecord.logTitle}"+
                        "        </td>"+
                        "        <td>"+
                        "            ${historyRecord.logDetails}"+
                        "        </td>"+
                        "        <td>"+
                        "            ${historyRecord.operator}"+
                        "       </td>"+
                        "        <td>"+
                        "            ${historyRecord.createdTime?string(\'yyyy-MM-dd HH:MM:ss\')}"+
                        "        </td>"+
                        "    </tr>"+
                        "</#list>"+
						"</table><br></#if>";/*);
					windows('historyRecord_win'+name,{open:function(){
						do_js_beautify('historyRecord_html'+name);
					}});*/
			}else if(val=="cimInfos"){
				value="<#if (variables.ciInfos?exists && variables.ciInfos?size>0) ><br><table class=\"table_border\">" +
					"<tr>"+
	                " <td>" + i18n.lable_ci_assetNo + "</td> " +
	                " <td>" + i18n.title_asset_name + "</td>" +
	                " <td>" + i18n.CICategory + "</td>"+
	                " <td>" + i18n.status + "</td>"+
	                "</tr>"+
	                "<#list variables.ciInfos as ciDTO><tr>"+
                    " <td>${ciDTO.cino}</td>" +
                    " <td>${ciDTO.ciname}</td>" +
                    " <td>${ciDTO.categoryName}</td>"+
                    " <td>${ciDTO.status}</td>"+
                    "</tr></#list>"+
					"</table></#if>";
			}else if(val=="createDate"){
				value="${variables.createdOn?string(\'yyyy-MM-dd HH:MM:ss\')}";
			}else if(val!=null && val!=""){
				value="$"+val;
			}
			wstuo.noticeRule.noticeGrid.insertAtCursor($("#eventObj"+name).val(),value);
		},
		
		//插入光标处
		insertAtCursor:function(eventId,myValue){
			if(eventId){
				var myField=document.getElementById(eventId);
				//IE support
				if (document.selection)
				{
					myField.focus();
					sel = document.selection.createRange();
					sel.text = myValue;
					sel.select();
				}
				//MOZILLA/NETSCAPE support
				else if (myField.selectionStart || myField.selectionStart == '0')
				{
					var startPos = myField.selectionStart;
					var endPos = myField.selectionEnd;
					// save scrollTop before insert
					var restoreTop = myField.scrollTop;
					myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos,myField.value.length);
					if (restoreTop > 0)
					{
						// restore previous scrollTop
						myField.scrollTop = restoreTop;
					}
					myField.focus();
					myField.selectionStart = startPos + myValue.length;
					myField.selectionEnd = startPos + myValue.length;
				} else {
					myField.value += myValue;
					myField.focus();
				}
			}
		},
		/**
		 * 添加通知模板
		 */
		addNoticeRule:function(){
			
			//if($('#addNoticesForm').form('validate')&&$('#noticeMailFrom').form('validate')){
				var noticeRuleType="";
				$('input[name="noticeRuleTypeAdd"]:checked').each(function(){
					noticeRuleType+=$(this).val()+';';
				});
				var mail = $("#addEmailMethodInput").val() ;
				var noticeName = $("#noticeNameAdd").val() ;
				var technicians = $("#addTechnicianMethodInput").val();
				var fm = $('#addNoticesForm').serialize()+'&'+$('#noticeMailFrom').serialize()+'&noticeRuleDTO.technician='+technicians+'&noticeRuleDTO.noticeRuleType='+noticeRuleType+'&noticeRuleDTO.emailAddress='+mail;
			
				var content=$('#emailAdd_templateContent').val();
				/*var content="";
				if(CKEDITOR.instances['emailAdd_templateContent']){
					var oEditor = CKEDITOR.instances.emailAdd_templateContent;
					content = oEditor.getData();
				}*/
		
				if(trim(noticeName)==""){
					msgAlert(i18n.noticeRuleModule_Name,'info');
				}else if(trim(content)==""){
					msgAlert(i18n.noticeRuleModule_Content_required,'info');
				}else{
					validateUsersByLoginName(technicians,function(){
						$('#emailAdd_templateContent').val(content);
						if(checkEmail(mail,true)){
							startProcess();
							
							$.post("noticeRule!addNotices.action",fm, function(res){
								endProcess();
								
								basics.index.initContent("../pages/wstuo/sysMge/sysMge_noticeGrid.jsp");
								msgShow(i18n.addSuccess,'show');
							});
						}else{
							msgAlert(i18n.emailFormatError,'info');
						}
					});
				}
		//	}
		},
		/**
		 * 打开搜索面板
		 */
		opendoSearch:function(){
			windows('noticeSearchWin',{width:550,modal: true});
			//禁止回车事件
			$("#noticeNameSearch").keydown(function (e) {
	            var curKey = e.which;
	            if (curKey == 13) {
	                return false;
	            }
	        });
		},
		delConfirmCheck:function(id){

			msgConfirm(i18n.msg_msg,'<br/>'+i18n.msg_confirmDelete,function(){
				wstuo.noticeRule.noticeGrid.delNoticeRules(id);
			});
		},
		delete_notices_aff:function(){
          checkBeforeDeleteGrid('#noticeGrid',wstuo.noticeRule.noticeGrid.delNoticeRules);
        },
        /**
         * 删除模板
         */
		delNoticeRules:function(rowIds){
			
			var _param = $.param({'ids':rowIds},true);
			$.post("noticeRule!delNoticeRules.action",_param, function(res){
				
				msgShow(i18n.deleteSuccess,'show');
				$('#noticeGrid').trigger('reloadGrid');
			});
		},
		edit_notices_aff:function(){
			checkBeforeEditGrid('#noticeGrid',wstuo.noticeRule.noticeGrid.editNoticeRules);
        },
        /**
         * 进入编辑规则页面
         */
       /* editNoticeRules:function(rowData){
          basics.tab.tabUtils.refreshTab(i18n.editNoticeRule,"noticeRule!findByFileName.action?noticeRuleDTO.noticeRuleId="+rowData.noticeRuleId);
        },*/


        editNoticeRules:function(rowData){
			
        	basics.index.initContent("noticeRule!findByFileName.action?noticeRuleDTO.noticeRuleId="+rowData.noticeRuleId);
		},
		
		/**
		 * 选择技术员
		 */
		selectNoticeUser:function(inputId,showType){
			wstuo.user.userUtil.selectUserMulti(inputId,'',showType,'-1');
		},
		changeNoticeObject:function(value,type){
			$("#nrtr"+type).removeAttr("style");
			$("#nrRequest"+type).attr("style","display:none;"); 
			$("#nrTechnician"+type).attr("style","display:none;"); 
			$("#nrTechnicalGroup"+type).attr("style","display:none;"); 
			$("#nrCiOwner"+type).attr("style","display:none;"); 
			$("#nrCiUse"+type).attr("style","display:none;"); 
			$("#nrOwner"+type).attr("style","display:none;"); 
			$("#nrTechnicalGroupLeader"+type).attr("style","display:none;"); 
			
			if(value=="request"){
				$("#nrRequest"+type).removeAttr("style");
				$("#nrTechnician"+type).removeAttr("style"); 
				$("#nrTechnicalGroup"+type).removeAttr("style"); 
				$("#nrTaskGroupAndTechnician"+type).removeAttr("style"); 
				$("#nrTechnicalGroupLeader"+type).removeAttr("style"); 
				$("#nrOwner"+type).removeAttr("style");
				$("input[name='noticeRuleType"+type+"']").removeAttr("checked"); 
				wstuo.noticeRule.noticeGrid.loadVariable("#variableValueAdd","request");
			}else if(value=="problem"){
				$("#nrRequest"+type).removeAttr("style");
				$("#nrTechnician"+type).removeAttr("style"); 
				$("#nrTechnicalGroup"+type).removeAttr("style");
				$("#nrTechnicalGroupLeader"+type).removeAttr("style"); 
				$("#nrTaskGroupAndTechnician"+type).removeAttr("style"); 
				$("input[name='noticeRuleType"+type+"']").removeAttr("checked");
				wstuo.noticeRule.noticeGrid.loadVariable("#variableValueAdd","problem");
			}else if(value=="change"){
				$("#nrRequest"+type).removeAttr("style");
				$("#nrTechnician"+type).removeAttr("style"); 
				$("#nrTechnicalGroup"+type).removeAttr("style");
				$("#nrTechnicalGroupLeader"+type).removeAttr("style"); 
				$("#nrTaskGroupAndTechnician"+type).removeAttr("style"); 
				$("input[name='noticeRuleType"+type+"']").removeAttr("checked"); 
				wstuo.noticeRule.noticeGrid.loadVariable("#variableValueAdd","change");
			}else if(value=="cim"){
				$("#nrCiOwner"+type).removeAttr("style");
				$("#nrCiUse"+type).removeAttr("style"); 
				$("input[name='noticeRuleType"+type+"']").removeAttr("checked");
				wstuo.noticeRule.noticeGrid.loadVariable("#variableValueAdd","cim");
			}else if(value=="release"){
				$("#nrRequest"+type).removeAttr("style");
				$("#nrTechnician"+type).removeAttr("style"); 
				$("input[name='noticeRuleType"+type+"']").removeAttr("checked"); 
				wstuo.noticeRule.noticeGrid.loadVariable("#variableValueAdd","release");
			}else if(value=="task"){
				$("#nrRequest"+type).removeAttr("style");
				$("#nrOwner"+type).removeAttr("style");
				$("input[name='noticeRuleType"+type+"']").removeAttr("checked"); 
			}else if(value=="other"){
				$("#nrRequest"+type).removeAttr("style");
				$("#nrTechnician"+type).removeAttr("style"); 
				$("#nrTechnicalGroup"+type).removeAttr("style"); 
				$("input[name='noticeRuleType"+type+"']").removeAttr("checked"); 
			}else{
				$("#nrtr"+type).attr("style","display:none;");
				$("input[name='noticeRuleType"+type+"']").removeAttr("checked"); 
			}
		},
		
		/**
		 * 加载变量
		 * @param selectId 下拉框id
		 * @param type 模板类型
		 */
		loadVariable:function(selectId,type){
			$(selectId).html('');
			$(selectId).append('<option value="">--'+i18n.pleaseSelect+'--</option>');
			var variableStr ='';
			if(type=='request'){
				variableStr="ecode,etitle,edesc,ecategoryName,createdByName,historyRecord,seriousnessName," +
				"priorityName,statusName,imodeName,levelName,assigneeGroupName,assigneeName,solutions," +
				"createDate,outcome,activityName,operator";
				
			}else if(type=="problem"){
				variableStr="ecode,etitle,edesc,ecategoryName,createdByName,historyRecord,seriousnessName," +
				"priorityName,statusName,levelName,assigneeGroupName,assigneeName," +
				"createDate,ciname,activityName,operator";
				
			}else if(type=="change"){
				variableStr="ecode,etitle,edesc,ecategoryName,createdByName,historyRecord,seriousnessName," +
				"priorityName,statusName,levelName,assigneeGroupName,assigneeName," +
				"createDate,outcome,activityName,operator,cimInfos";
				
			}else if(type=="cim"){
				variableStr="ecategoryName,statusName,createDate,ciname";
				
			}else if(type=="release"){
				variableStr="ecode,etitle,edesc,ecategoryName,createdByName,historyRecord," +
						"statusName,levelName,assigneeName," +
						"createDate,outcome,activityName,operator";
				
			}else if(type=='task'){
				variableStr="etitle,edesc,createdByName,planTime,createDate";
			}
			var vars = variableStr.split(',');
			
			for(var i=0;i<vars.length;i++){
				$(selectId).append(variables[vars[i]]);
			}
			
		},
		init:function(){
			wstuo.noticeRule.noticeGrid.showNotice();
		}
	};
}();
$(document).ready(wstuo.noticeRule.noticeGrid.init);